package cn.nawang.ebeim.api.repository.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;

import cn.nawang.ebeim.api.comm.BaseQuery;
import cn.nawang.ebeim.api.comm.PageList;
import cn.nawang.ebeim.api.comm.Pages;
import cn.nawang.ebeim.api.domain.StorageServer;
import cn.nawang.ebeim.api.utils.ConvertUtil;

/**
 * @ClassName: StorageCloudRepositoryImpl
 * @Description: TODO
 * @author fanyb
 * @date Aug 18, 2015 9:13:18 AM
 * @version v1.0
 */
@Repository
public class StorageServerRepositoryImpl extends BaseQuery {

  public PageList findAllByPaging(Pages page) {
    String hqlCount = "select count(ss.id) from StorageServer ss,StorageCloud sc where ss.storageCloudId=sc.id and 1=1 ";
    String hqlList = "select new cn.nawang.ebeim.api.domain.StorageServer(ss.id,ss.host,ss.port,"
        + "ss.storageCloudId, ss.internalHost, ss.internalPort, sc.name) "
        + "from StorageServer ss,StorageCloud sc where ss.storageCloudId=sc.id and 1=1 ";
    String order = " order by ss.id desc";
    PageList pl = null;
    try {
      String cod = joinSearchCondition(page);// 拼接查询条件
      pl = queryListByPaging(hqlCount + cod + order, hqlList + cod + order, page);
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    return pl;
  }

  public boolean delete(String[] ids) {
    try {
      String values = ConvertUtil.toDbString(ids);
      String hqlList = "delete from StorageServer where id in" + values;
      Map<String, Object> paraMap = new HashMap<String, Object>();
      boolean deleteFlag = this.execHQL(hqlList, paraMap);
      return deleteFlag;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return false;
  }

  public StorageServer findByIpAndPort(String host, int port) {
    String hql = "from StorageServer where host=:host and port=:port";
    Map<String, Object> paraMap = new HashMap<String, Object>();
    try {
      paraMap.put("host", host);
      paraMap.put("port", port);
      List<StorageServer> storageServers = queryObject(hql, paraMap);
      if (storageServers != null && !storageServers.isEmpty()) {
        return storageServers.get(0);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
}
